package com.glodon.paas.mail;

import static javax.ws.rs.core.MediaType.*;

import javax.ws.rs.core.MultivaluedMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.util.ObjectUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class MailClientHttpImpl implements MailClient{
	private Logger logger = LoggerFactory.getLogger(MailClientHttpImpl.class);
	private String mailApiUrl = "http://172.16.107.244:8080/account/api/internal"; 
	private boolean enable = true;

	public String getMailApiUrl() {
		return mailApiUrl;
	}

	public void setMailApiUrl(String mailApiUrl) {
		this.mailApiUrl = mailApiUrl;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	@SuppressWarnings("deprecation")
	public int sendMail(MailMessageParam message,boolean async){
		if(!enable){
			return 0;
		}
		
		try {
			// 参数
			MultivaluedMap<String, String> params = new MultivaluedMapImpl();
		    params.add("async", "false");
			ClientResponse c = createResource().path("sendMail").queryParams(params).accept(APPLICATION_JSON_TYPE)
								.entity(message).post(ClientResponse.class);

		    if(c.getStatus() == 204){	    	
		        //成功，返回值是null
		    	if(logger.isDebugEnabled()){
			    	logger.debug("send mail ok:"+ObjectUtil.toJson(message));	    		
		    	}
		        return 200;
		    }else if(c.getStatus() == 200){
		    	if(logger.isDebugEnabled()){
				    logger.debug("send mail ok:"+ObjectUtil.toJson(message));	    		
		    	}
		    	return c.getStatus() ;
		    }else{
		    	logger.error("send mail error:" + ObjectUtil.toJson(message));
		    	logger.error("ResponseStatus=" + c.getResponseStatus());	    	
		    	return c.getStatus() ;
		    }
		} catch (Exception e) {
			logger.error("send mail error:" + e.getMessage(), e);
			throw PaasServerExceptionFactory.internalAPIException("send mail error"+e.getMessage(), e);
		}		
	}
 
	static WebResource webResource;
	public WebResource createResource() {
		if(webResource == null){
			ClientConfig config = new DefaultClientConfig();
			Client client = Client.create(config);
			webResource = client.resource(mailApiUrl);			
		}
		return webResource;
	}
}
